package com.carl.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.carl.common.utils.HttpUtils;
import com.carl.mall.member.entity.MemberLevelEntity;
import com.carl.mall.member.exception.PhoneExistException;
import com.carl.mall.member.exception.UserNameExistException;
import com.carl.mall.member.service.MemberLevelService;
import com.carl.mall.member.vo.MemberLoginVO;
import com.carl.mall.member.vo.MemberRegisterVO;
import com.carl.mall.member.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carl.common.utils.PageUtils;
import com.carl.common.utils.Query;

import com.carl.mall.member.dao.MemberDao;
import com.carl.mall.member.entity.MemberEntity;
import com.carl.mall.member.service.MemberService;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {


    @Autowired
    private MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 会员注册功能
     * @param memberRegisterVO
     */
    @Override
    public void register(MemberRegisterVO memberRegisterVO) throws PhoneExistException,UserNameExistException{
        if (log.isInfoEnabled()){
            log.info("MemberServiceImpl.register.memberRegisterVO:{}", JSON.toJSONString(memberRegisterVO));
        }

        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity memberLevelEntity = memberLevelService.queryMemberLevelDefault();
        memberEntity.setUsername(memberRegisterVO.getUserName());
        memberEntity.setNickname(memberRegisterVO.getUserName());  //设置昵称为用户名  后期用户可以自己改
        memberEntity.setMobile(memberRegisterVO.getPhone());
        memberEntity.setCreateTime(new Date());
        memberEntity.setLevelId(memberLevelEntity.getId());

        //用户名和手机号不能重复
        checkUsernameUnique(memberRegisterVO.getUserName());
        checkPhoneUnique(memberRegisterVO.getPhone());

        //设置密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String passWord = encoder.encode(memberRegisterVO.getPassword());
        memberEntity.setPassword(passWord);
        this.save(memberEntity);
        if (log.isInfoEnabled()){
            log.info("MemberServiceImpl.register.save:{}", JSON.toJSONString(this.save(memberEntity)));
        }

    }

    @Override
    public MemberEntity login(MemberLoginVO memberLoginVO) {
        //1.根据账号或者手机号查询会员信息
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", memberLoginVO.getUserName())
                .or().eq("mobile", memberLoginVO.getPhone()));
        if (memberEntity != null){
            //2.如果账号和手机号存在,然后根据密码加密后的校验来判断是否登录成功
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(memberLoginVO.getPassword(), memberEntity.getPassword());
            if (matches){
                //表明登陆成功 //密码是匹配的
                return memberEntity;
            }
        }
        //如果没查到直接返回返回null 交给展示层进行处理  展示层判断是否结果是否存在就行
        return null;
    }

    /**
     * 社交登录 和普通的账号登录走的两个逻辑等于在数据库中有两条记录
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) {
        String uid = socialUser.getUid();
        // 如果不是第一次社交登录 那么就更新相关信息 登录功能
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("social_id", uid));
        if (memberEntity != null){
            // 说明当前用户已经注册过了，表里有用户信息 更新token和过期时间
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(socialUser.getAccessToken());
            entity.setExpireIn(socialUser.getExpiresIn());
            this.updateById(entity);
            // 在返回的登录用户信息中我们同步的也保存 token和过期时间
            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpireIn(socialUser.getExpiresIn());
            return memberEntity;
        }
        // 表示用户是第一次提交，那么我们就需要对应的来注册
        MemberEntity entity = new MemberEntity();
        entity.setAccessToken(socialUser.getAccessToken());
        entity.setExpireIn(socialUser.getExpiresIn());
        entity.setSocialUid(socialUser.getUid());
        //  通过token调用微博开发的接口来获取用户的相关信息
        try {
            //根据官方文档 查看要用到的接口需要什么参数，构建查询条件
            HashMap<String, String> querys = new HashMap<>();
            querys.put("access_token",socialUser.getUid());
            querys.put("uid",socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com"
                    , "/2/users/show.json"
                    , "get"
                    , new HashMap<>()
                    , querys
            );
            if (response.getStatusLine().getStatusCode() == 200){
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String nickName = jsonObject.getString("screen_name");
                String gender = jsonObject.getString("gender");
                entity.setNickname(nickName);
                entity.setGender("m".equals(gender)?0:1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //注册用户信息
        this.save(entity);
        return entity;
    }

    /**
     * 校验手机号是否存在
     * @param phone
     * @throws PhoneExistException
     */
    private void checkPhoneUnique(String phone) throws PhoneExistException {
        int mobile = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (mobile > 0){
            throw new PhoneExistException();
        }

    }

    /**
     * 校验用户昵称是否存在
     * @param userName
     * @throws UserNameExistException
     */
    private void checkUsernameUnique(String userName) throws UserNameExistException {

        int username = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (username > 0) {
            throw new UserNameExistException();
        }
    }

}